<template>
	<su-fixed  noNav :index="1100" placeholder >
		<su-status-bar v-if="!sheep.$platform.inApp" />
		<view class="navbar" :style="{paddingBottom: (44* state.navOpacity) + 'px'}">
			<view class="navbar-center ss-flex ss-col-bottom" >
				<view class="ss-flex w-100" style="height: 44px;">
					<view class="ss-flex-1 ss-flex ss-row-between ss-p-x-20 w-100">
						<view class="leftBox ss-flex" :style="{opacity:state.navOpacity}">
							<view class="leftBox-location ss-flex " 
								@click="onchangeArea">
								<uni-icons type="location-filled" size="26" color="#333" />
								<view class="location-name">{{ state.params.area }}</view>
								<image class="location-icon" src="/static/tuangou/right.png" mode="aspectFill" />
							</view>
							<image :src="sheep.$url.cdn('/static/user/kefu1.png')" v-if="isAuditMode==false"
								style="width:40rpx;height:40rpx;" class="ss-m-l-20" @click="showKefu" />
							<uni-icons class="qr_code"  @click="openScanCode" type="scan" size="22"></uni-icons>
							<!-- <image class="qr_code"  :src="sheep.$url.cdn('/static/home/imgs/sm.png','ygb')"
								mode="aspectFill" /> -->
						</view>
					</view>
					<!-- #ifdef MP -->
					<view v-if="!sheep.$platform.inPc" :style="[capsuleStyle]"></view>
					<!-- #endif -->
					<view v-if="sheep.$platform.inApp" :style="[capsuleStyle]"></view>
				</view>
			</view>
			<view class="search" :style="{
				paddingTop :`calc(5px + ${Number(sys_statusBar) + (44 * state.navOpacity)}px)`,
				height:`calc( 44px + ${Number(sys_statusBar) + (44 * state.navOpacity)}px)`,
				background:`rgba(255,255,255,${1 - state.navOpacity})`,
				paddingLeft: 15 + (0*( 1 - state.navOpacity)) + 'px',
				paddingRight: 15 + (capsuleWidth*(1 - state.navOpacity)) + 'px'}">
				<view class="search-box ss-flex ss-row-between">
					<view class="city" @click="onchangeArea">
						<view class="city_name">{{ state.params.area }}</view>
						<image class="down" src="/icon/down.png" mode="aspectFill" />
					</view>
					<view class="line"></view>
					<input type="text" class="keyword" @confirm="inputSearch" v-model="state.params.title"
						:placeholder="data.searchText ? data.searchText :'输入搜索内容'" />
					<view class="search_btn" @click="onSearch">搜索</view>
				</view>
			</view>
		</view> 
	</su-fixed>
</template>

<script setup>
	import sheep from '@/sheep';
	import {
		ref,
		reactive,
		computed,
		nextTick,
		getCurrentInstance,
	} from 'vue'
	import {
		onLoad,
		onShow,
		onHide,
		onPageScroll,
		onReachBottom,
		onPullDownRefresh
	} from '@dcloudio/uni-app';
	import {
		showKefuModal
	} from '@/sheep/hooks/useModal';
	import { showAuditModal } from "@/sheep/hooks/useAudit.js"
	const isAuditMode = computed(() => sheep.$store('app').isAuditMode);
	const location = sheep.$store('location')
	 const sys_statusBar = sheep.$platform.device.statusBarHeight;
	const props = defineProps({
	  data: {
	    type: Object,
	    default: () => ({}),
	  },
	  styles: {
	    type: Object,
	    default: () => ({}),
	  },
	});
	const state = reactive({
		navOpacity: 1,
		scrollTop:0,
		params: {
			area: '杭州市',
			tag_id:'',
			title: '',
			lng: location.myPosition.longitude,
			lat: location.myPosition.latitude,
		},
	})
	onLoad(async (opt) => {
		await getLocation()
	})
	onPageScroll((e) => {
		state.scrollTop = e.scrollTop
		let navTran = (30 - e.scrollTop) / 30
		// let classTran = (75 - e.scrollTop) / 75
		if (navTran >= 1) {
			state.navOpacity = 1
		} else if (navTran <= 0) {
			state.navOpacity = 0
		} else {
			state.navOpacity = navTran.toFixed(2)
		}

	})
	function showKefu(){
		showKefuModal()
	}
	const hasHistory = sheep.$router.hasHistory();
	function onClickLeft() {
		if (hasHistory) {
			sheep.$router.back();
		} else {
			sheep.$router.go('/pages/index/home');
		}
	}
	async function getLocation(){
		try{
			let data = await location.getLocation()
			state.params.lat = data.latitude
			state.params.lng = data.longitude
			sheep.$store('location').$patch((store) => {
			  store.myPosition.longitude = data.longitude
			  store.myPosition.latitude = data.latitude
			});
			analyzeLocation(data)
		}catch(e){
			state.params.lat = location.myPosition.latitude
			state.params.lng = location.myPosition.longitude
			
		}
	}
	async function analyzeLocation({latitude,longitude}){
		let { data , error} = await sheep.$api.app.getLocation({
			latitude,longitude
		})
		if(error == 0){
			console.log('data',data,state.params.lon)
			state.params.area = data?.city || data?.district
			uni.setStorageSync("location",JSON.stringify({
				city_name : state.params.area,
				longitude : state.params.lon,
				latitude : state.params.lat,
			}))
		}
	}
	function inputSearch() {
		console.log('点击了搜索')
	}

	function onTap(data){
		console.log('onTap',data)
	}
	function onSearch() {
		sheep.$router.go('/pages/merchant/list',{
			search:state.params.title
		})
	}
	const capsuleWidth = computed(() => {
		// #ifdef MP
		if (!sheep.$platform.inPc) {
			return sheep.$platform.capsule.width
		}
		// #endif
		return 0
	});
	const capsuleStyle = computed(() => {
		return {
			width: sheep.$platform.capsule.width + 'px',
			minWidth: sheep.$platform.capsule.width + 'px',
			height: sheep.$platform.capsule.height + 'px',
			margin: '0 ' + (sheep.$platform.device.windowWidth - sheep.$platform.capsule.right) + 'px 0 0',
		};
	});

	function changeAddress() {
		if (uni.getStorageSync('location')) {
			state.location = JSON.parse(uni.getStorageSync('location'));
			state.params.area = state.location.city_name;
			// state.params.lng = state.location.lon;
			// state.params.lat = state.location.lat;
	
		}
	};
	// 切换城市
	function onchangeArea() {
		// #ifdef APP
		showAuditModal(
		  'ACCESS_FINE_LOCATION',
		  () => {
		// #endif
			uni.navigateTo({
				url: '/pages/etc/chooseArea',
				events: {
					// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
					acceptDataFromOpenedPage: function(data) {
						changeAddress();
					},
				},
				success: function(res) {
					// 通过eventChannel向被打开页面传送数据
					res.eventChannel.emit('acceptDataFromOpenerPage', {});
				},
			});
		// #ifdef APP
		},
		  null,
		  false,
		);
		// #endif
	};
	
	function openScanCode() {
	
	  // #ifdef APP
	  showAuditModal(
	    'WRITE_EXTERNAL_STORAGE,CAMERA',
	    () => {
		// #endif
	  uni.scanCode({
	    success: async function (res) {
		  // 团购绑定人员
		  if (res.result.indexOf('bind') !== -1) {
		  	const obj = res.result.split('&').reduce((acc, item) => {
		  	  const [key, value] = item.split('=');
		  	  acc[key] = decodeURIComponent(value);
		  	  return acc;
		  	}, {});
		  	return sheep.$router.go('/pages/merchant/bindCheck',{
		  		id:obj.store_id,
		  		code:obj.code
		  	})
		  }
		  
		  // 团购核销
		  if (res.result.indexOf('code') !== -1) {
		  	const obj = res.result.split('&').reduce((acc, item) => {
		  	  const [key, value] = item.split('=');
		  	  acc[key] = decodeURIComponent(value);
		  	  return acc;
		  	}, {});
		  	
		  	const {
		  		error,
		  		data
		  	} = await sheep.$api.merchant.checkCode({
		  		code: obj.code
		  	})
		  	
		  	if (error === 0) {
		  		uni.showModal({
		  			title: '提示',
		  			content: '核销成功！',
		  			success: function(res) {
		  			}
		  		});
		  	}
		  	
		  	return 
		  }
		  
	    },
		fail: (err) => {
			console.log('--------',err)
		}
	  });
	  // #ifdef APP
	  },
	    null,
	    false,
	  );
	  // #endif
	}
</script>

<style lang="scss" scoped>
	view {
		box-sizing: border-box;
	}
	
	::v-deep .input-placeholder{
		color: #666 !important;
	}
	.navbar {
		.navbar-center {
			width: 100vw;
			height: 44px;
			max-width: 100vw;
			position: relative;
			top: 0;
			z-index:10;

			.leftBox {
				.leftBox-iconBox{
					padding-left: 14rpx;
					padding-right: 20rpx;
					.leftBox-icon {
						width: 14rpx;
						height: 37rpx;
						vertical-align: middle;
					}
				}
				
				.leftBox-title {
					font-size: 36rpx;
					font-weight: 500;
					line-height: normal;
					text-align: center;
					color: #000000;
				}

				.leftBox-location {
					.location-name {
						font-size: 15px;
						font-weight: 500;
						line-height: normal;
						text-align: center;
						color: #2C2C2C;
					}

					.location-icon {
						margin-left: 6rpx;
						width: 24rpx;
						height: 24rpx;
						vertical-align: middle;
					}
				}
			}

			.rightBox {
				padding-right: 14rpx;

				.rightBox-icon {
					margin-right: 4rpx;
					width: 24rpx;
					height: 24rpx;
					vertical-align: middle;
				}

				font-size: 26rpx;
				font-weight: 500;
				line-height: normal;
				text-align: center;
				color: #2C2C2C;
			}
		}
	}


	.search {
		position: absolute;
		top:0;
		width: 100%;
		height: 44px;
		z-index: 20;
		padding: 5px 30rpx;
		transition: 0.1s;
		pointer-events:none;
		.search-box {
			transition: 0.1s;
			height: 34px;
			border-radius: 50rpx;
			background-color: #EfEfEf;
			padding-left: 20rpx;
			pointer-events:auto;
		}

		.city {
			display: flex;
			align-items: center;
			width: 130rpx;
			padding: 0 20rpx 0 0;
			// background-color: aqua;
			justify-content: space-between;

			.city_name {
				color: #000000;
				font-weight: 500;
				font-size: 15px;
				width: 120rpx;
				text-align: center;
				overflow: hidden; //超出的文本隐藏
				text-overflow: ellipsis; //溢出用省略号显示
				white-space: nowrap; //溢出不换行
			}

			.down {
				width: 18rpx;
				height: 6px;
			}
		}

		.line {
			width: 4rpx;
			height: 20px;
			background-color: #e9e9e9;
		}

		.keyword {
			font-size: 15px;
			flex: 1;
			height: 22px;
			font-weight: 500;
			color: #000;
			margin-left: 20rpx;
		}

		.search_btn {
			padding: 4px 25rpx;
			margin-right: 10rpx;
			color: #fff;
			font-size: 14px;
			border-radius: 40rpx;
			background: linear-gradient(180deg, #8487DB 0%, #E4B3E9 100%);

		}
	}
	.qr_code {
		margin-left: 20rpx;
		border-radius: 10rpx;
		font-weight: bold;
	}
</style>